"""
GitCode API客户端单元测试
"""
import os
import pytest
import aiohttp
from unittest.mock import AsyncMock, patch, MagicMock

from gitcode_mcp.api import GitCodeAPI, GitCodeAPIError


@pytest.fixture
def mock_env(monkeypatch):
    """模拟环境变量"""
    monkeypatch.setenv("GITCODE_TOKEN", "test-token")


@pytest.fixture
def api_client(mock_env):
    """创建API客户端实例"""
    return GitCodeAPI()


@pytest.mark.asyncio
async def test_ensure_session(api_client):
    """测试确保会话方法"""
    # 首次调用应创建新会话
    session = await api_client.ensure_session()
    assert isinstance(session, aiohttp.ClientSession)
    assert api_client._session is session
    
    # 再次调用应返回相同会话
    session2 = await api_client.ensure_session()
    assert session2 is session


@pytest.mark.asyncio
async def test_request_success():
    """测试成功的请求"""
    with patch('aiohttp.ClientSession') as mock_session:
        # 设置模拟响应
        mock_response = AsyncMock()
        mock_response.status = 200
        mock_response.json.return_value = {"success": True}
        
        # 设置模拟会话
        mock_session_instance = MagicMock()
        mock_session_instance.request.return_value.__aenter__.return_value = mock_response
        mock_session.return_value = mock_session_instance
        
        # 创建客户端并调用方法
        api_client = GitCodeAPI("test-token")
        result = await api_client.request("GET", "/test")
        
        # 验证结果
        assert result == {"success": True}
        mock_session_instance.request.assert_called_once_with("GET", "https://api.gitcode.com/api/v5/test")


@pytest.mark.asyncio
async def test_request_error():
    """测试失败的请求"""
    with patch('aiohttp.ClientSession') as mock_session:
        # 设置模拟错误响应
        mock_response = AsyncMock()
        mock_response.status = 404
        mock_response.text.return_value = "Not Found"
        
        # 设置模拟会话
        mock_session_instance = MagicMock()
        mock_session_instance.request.return_value.__aenter__.return_value = mock_response
        mock_session.return_value = mock_session_instance
        
        # 创建客户端并调用方法
        api_client = GitCodeAPI("test-token")
        
        # 验证抛出异常
        with pytest.raises(ValueError):
            await api_client.request("GET", "/test") 